package com.tanhua.server.service;

import cn.hutool.core.collection.CollUtil;
import com.tanhua.autoconfig.template.HuanXinTemplate;
import com.tanhua.commons.utils.Constants;
import com.tanhua.dubbo.api.CommentApi;
import com.tanhua.dubbo.api.FriendApi;
import com.tanhua.dubbo.api.UserApi;
import com.tanhua.dubbo.api.UserInfoApi;
import com.tanhua.model.domain.User;
import com.tanhua.model.domain.UserInfo;
import com.tanhua.model.enums.CommentType;
import com.tanhua.model.mongo.Comment;
import com.tanhua.model.mongo.Friend;
import com.tanhua.model.vo.*;
import com.tanhua.server.exception.BusinessException;
import com.tanhua.server.interceptor.UserHolder;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Service
public class MessagesService {
    @DubboReference
    private UserApi userApi;
    @DubboReference
    private UserInfoApi userInfoApi;
    @Autowired
    private HuanXinTemplate huanXinTemplate;
    @DubboReference
    private FriendApi friendApi;
    @DubboReference
    private CommentApi commentApi;

    //根据环信用户id，查询用户信息
    public UserInfoVo findByUserInfoHuanxin(String huanxinId) {
        //根据环信查找用户
        User user = userApi.findByHuanXin(huanxinId);
        //根据用户id查询用户详情
        UserInfo userInfo = userInfoApi.findById(user.getId());
        UserInfoVo vo = new UserInfoVo();
        //将拷贝信息
        BeanUtils.copyProperties(userInfo, vo);
        if (userInfo.getAge() != null) {
            vo.setAge(userInfo.getAge().toString());
        }
        //构建vo返回值
        return vo;
    }

    /**
     * 添加联系人
     *
     * @param friendId
     */
    public void addContacts(Long friendId) {
        //将好友关系绑定到环信
        Boolean aBoolean = huanXinTemplate.addContact(Constants.HX_USER_PREFIX + UserHolder.getUserId(), Constants.HX_USER_PREFIX + friendId);
        //判断是否绑定成功
        if (!aBoolean) {
            throw new BusinessException(ErrorResult.FriendError());
        }
        //如果好友关系成功绑定到环信，保存信息
        friendApi.save(UserHolder.getUserId(), friendId);
    }

    /**
     * 删除联系人
     * @param friendId
     */
    public void deleteContacts(Long friendId) {
        //将好友关系绑定到环信
        Boolean aBoolean = huanXinTemplate.deleteContact(Constants.HX_USER_PREFIX + UserHolder.getUserId(), Constants.HX_USER_PREFIX + friendId);
        //判断是否绑定成功
        if (!aBoolean) {
            throw new BusinessException(ErrorResult.FriendError());
        }
        //如果环信好友关系已经解绑，删除本地好友关系数据
        friendApi.delete(UserHolder.getUserId(), friendId);
    }


    /**
     * 查询好友列表
     *
     * @param page
     * @param pagesize
     * @param keyword
     * @return
     */
    public PageResult fandAllcontacts(Integer page, Integer pagesize, String keyword) {
        //查询好友信息
        List<Friend> friends = friendApi.fandAllcontacts(UserHolder.getUserId(), page, pagesize);
        //判断有无好友信息
        if (CollUtil.isEmpty(friends)) {
            return new PageResult();
        }
        //提取好友列表的id
        List<Long> friendIds = CollUtil.getFieldValues(friends, "friendId", Long.class);
        UserInfo userInfo = new UserInfo();
        //设置用户名关键字
        userInfo.setNickname(keyword);
        //调用api查询所有好友详情
        Map<Long, UserInfo> map = userInfoApi.findByIds(friendIds, userInfo);

        List<ContactVo> vos = new ArrayList<>();
        //构建vo对象，遍历好友列表
        for (Friend friend : friends) {
            //通过好友id获取每一个好友详情
            UserInfo userInfo1 = map.get(friend.getFriendId());
            //判断好友详情是否为空
            if (userInfo1 != null) {
                //构建vo
                ContactVo vo = ContactVo.init(userInfo1);
                //将每一个好友详情装入vos对象中
                vos.add(vo);
            }
        }
        return new PageResult(page, pagesize, 0, vos);
    }

    /**
     * 点赞列表
     *
     * @param page
     * @param pagesize
     * @return
     */
    public PageResult findLikes(Integer page, Integer pagesize, CommentType like) {
        //获取当前用户id
        Long userId = UserHolder.getUserId();
        //获取点赞的评论集合
        List<Comment> comments = commentApi.findLikeCommentsLove(userId, page, pagesize,like);
        return getPageResult(page, pagesize, comments, like);

    }

    /**
     * 评论列表
     *
     * @param page
     * @param pagesize
     * @return
     */
    public PageResult findAllComments(Integer page, Integer pagesize, CommentType comment) {
        //获取当前用户id
        Long userId = UserHolder.getUserId();
        //获取的评论集合
        List<Comment> comments = commentApi.findLikeCommentsLove(userId, page, pagesize,comment);
        return getPageResult(page, pagesize, comments, comment);
    }


    /**
     * 查询喜欢
     *
     * @param page
     * @param pagesize
     * @return
     */
    public PageResult findLoves(Integer page, Integer pagesize, CommentType love) {
        //获取当前用户id
        Long userId = UserHolder.getUserId();
        //获取喜欢的集合
        List<Comment> comments = commentApi.findLikeCommentsLove(userId, page, pagesize,love);
        return getPageResult(page, pagesize, comments, love);
    }

    /**
     * 公共的方法
     *
     * @param page
     * @param pagesize
     * @param comments
     * @param like
     * @return
     */
    private PageResult getPageResult(Integer page, Integer pagesize, List<Comment> comments, CommentType like) {
        if (CollUtil.isEmpty(comments)) {
            return new PageResult();
        }
        //获取所有点赞的人
        List<Long> userIds = CollUtil.getFieldValues(comments, "userId", Long.class);
        Map<Long, UserInfo> map = userInfoApi.findByIds(userIds, null);
        List<CommentVo> vos = new ArrayList<>();
        //遍历所有点赞的评论
        for (Comment comment : comments) {
            //获取一个人的详情
            UserInfo userInfo = map.get(comment.getUserId());
            if (userInfo != null) {
                CommentVo vo = CommentVo.init(userInfo, comment);
                vos.add(vo);
            }
        }
        return new PageResult(page, pagesize, 0, vos);
    }
}
